/****************
 *@description: 礼物收益账户管理  myPocket/userBalance/index
 *@author: Xhd
 *@API: 方子奥
 *@date: 2023-11-30 18:45:16
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from 'react';
import TheTable from "@/components/TheTable";
import ThePagination from "../../../components/ThePagination";
import TheButton from "@/components/TheButton";
import TheQueryForm from '@/components/TheQueryForm';
import VideoPlayer from "@/components/VideoPlayer"
import { getDateTime3 } from '@/utils/getDate'
import { apiGetGfitPage, apiGetGfitList } from '@/request/petCoins'
import store from "@/store/store"
import _ from 'lodash';
import {Space, Modal, Input, message} from "antd";
import Json2Excel from '@/utils/Json2Excel'

const { TextArea } = Input;
class screenAD extends Component {
  state = {
    columns: [
      {
        title: "会员ID",
        dataIndex: "memberId",
        key: "memberId",
      },
      {
        title: "用户昵称",
        dataIndex: "nickName",
        key: "nickName",
      },
      // {
      //   title: "实名姓名",
      //   dataIndex: "name",
      //   key: "name",
      // },
      {
        title: "会员手机号",
        dataIndex: "memberMobile",
        key: "memberMobile",
        render: (text) => {
          var reg = /^(\d{3})\d{4}(\d{4})$/;
          var memberMobile = text.toString().replace(reg, '$1****$2');
          return memberMobile;
        }
      },
      {
        title: "会员状态",
        dataIndex: "memberStatus",
        key: "memberStatus",
        render: (text, render) => {
          let txt = ''
          switch (text) {
            case "Y":
              txt = '正常'
              break;
            case "N":
              txt = '冻结'
              break;
            default:
              break;
          }
          return txt;
        },
      },
      {
        title: "现有收益额",
        dataIndex: "currentIncome",
        key: "currentIncome",
        render: text => text && <React.$price price={text} />,
      },
      {
        title: "冻结收益",
        dataIndex: "freezeEarnings",
        key: "freezeEarnings",
        render: text => text && <React.$price price={text} />,
      },
      {
        title: "可提现收益",
        dataIndex: "withdrawableIncome",
        key: "withdrawableIncome",
        render: text => text && <React.$price price={text} />,
      },
      {
        title: "账户状态",
        dataIndex: "accountStatusContent",
        key: "accountStatusContent",
        // render: (text, render) => {
        //   let txt = ''
        //   switch (text) {
        //     case 0:
        //       txt = '正常'
        //       break;
        //     case 1:
        //       txt = '封禁'
        //       break;
        //     default:
        //       break;
        //   }
        //   return txt;
        // }
      },
      {
        title: "操作",
        fixed: "right",
        width: 200,
        render: (text, render) => {
          return (
            <div>
              <TheButton haspermi={["myPocket:userBalance:accountDetail"]} onClick={() => this.goAccountDetail(render.memberId)}>详情</TheButton>
              <TheButton haspermi={["myPocket:userBalance:detail"]} onClick={() => this.goDetail(render.memberId)}>明细</TheButton>
            </div>
          );
        },
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    form_show: true,
    searchOption: [
      {
        field: 'memberTxt',
        label: '会员信息',
        placeholder: '输入会员ID/会员昵称/会员手机号',
        required: false,
        rules: [],
        type: 'Input',
        defaultValue: ''
      },
      {
        field: 'accountStatus',
        label: '账户状态',
        placeholder: '请选择',
        required: false,
        rules: [],
        type: 'Select',
        options: [{ value: 0, label: '正常' }, { value: 1, label: '封禁' }],
        defaultValue: ''
      },
      {
        field: 'income',
        label: '现有收益额',
        placeholder: '请输入',
        required: false,
        rules: [],
        type: 'NumRange',
        otherConfig: {
          precision: 2,
          max: 9999999.99,
          min: 0,
          minPlaceholder: '请输入最小收益额',
          maxPlaceholder: '请输入最大收益额'
        },
        minKey: 'incomeStart',
        maxKey: 'incomeEnd',
      },
    ],
    queryForm: {},
    stopReason: '',
    isvideoModalVisible: false,
    videoAddress: "",
    exportLoading: false
  };

  componentDidMount() {
    this.onColumnsFilter(this.state.columns)
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, queryForm, pathName } = searchParams
    if (searchParams && pageNo && pathName == 'userBalance') {
      this.setState({
        queryForm,
        pageData: {
          pageNo: pageNo, pageSize: pageSize
        }
      }, () => {
        this.queryFormRef.onSetDefault({
          ...queryForm
        })
        this.getData()
      })
    } else {
      this.getData()
    }
  };

  // 获取表格数据
  getData = async (values) => {
    let { pageNo, pageSize } = this.state.pageData
    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values }
    }, async () => {
      let { ...form } = { ...this.state.queryForm }
      const params = {
        pageNo,
        pageSize,
        queryForm: { ...form }
      }
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'userBalance',
          ...params
        }
      })
      form.incomeStart *= 100
      form.incomeEnd *= 100
      let res = await apiGetGfitPage({
        pageNo,
        pageSize,
        ...form,
      })
      if (res.code === 0 && res.data) {
        this.setState({
          dataSource: res.data.records,
          pageData: {
            pageNo: res.data.current,
            pageSize: res.data.size
          },
          total: res.data.total,
        })
      }
    })
  };

  goDetail = (id) => {
    this.props.history.push(`/myPocket/userBalance/detail/${id}`);
  };
  goAccountDetail = (id) => {
    this.props.history.push(`/myPocket/userBalance/accountDetail/${id}`,);
  };

  videoOk = async () => {
    this.setState({
      isvideoModalVisible: false,
      videoAddress: ""
    })
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => {
      this.getData()
    })
  };

  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }

  onColumnsFilter(value) {
    this.setState({
      newColumns: value
    })
  }

  onFormSearch(values) {
    let min = _.isNil(values.incomeStart) && _.isEmpty(values.incomeStart);
    let max = _.isNil(values.incomeEnd) && _.isEmpty(values.incomeEnd);
    if (min && !max){
      message.warning('请输入最小收益额')
    }
    else if (max && !min){
      message.warning('请输入最大收益额')
    }
    else {
      this.setState({
        pageData: { pageNo: 1, pageSize: 10 }
      }, () => {
        this.getData(values)
      })
    }
  }
  /**
   * @desc 表格数据导出
   * */
  toExport = async () => {
    const {queryForm} = this.state
    if (_.isEmpty(queryForm)) {
      Modal.warning({title: '请选择筛选条件并查询后再导出，暂不支持全量导出。',});
      return
    }
    else if (queryForm.incomeStart === undefined && queryForm.incomeEnd === undefined){
      Modal.warning({title: '请先输入现有收益额',});
      return
    }
    this.setState({exportLoading: true});
    queryForm.incomeStart *= 100
    queryForm.incomeEnd *= 100
    let res = await apiGetGfitList({
      ...queryForm,
    })
    if (res.code === 0) {
      let tB_data = res.data.map((item, index) => {
        return {
          ...item,
          index: index + 1,
          memberMobile: item.memberMobile.toString().replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2'),
          memberStatus: item.memberStatus === 'Y' ? '正常' : '冻结',
          currentIncome: React.$transNum(item.currentIncome || 0, 2, -2),
          freezeEarnings: React.$transNum(item.freezeEarnings || 0, 2, -2),
          withdrawableIncome: React.$transNum(item.withdrawableIncome || 0, 2, -2),
        };
      });
      const option = {
        header: [
          {prop: "memberId", title: "会员ID", valueType: 'n'},
          {prop: "nickName", title: "用户昵称"},
          {prop: "memberMobile", title: "会员手机号"},
          {prop: "memberStatus", title: "会员状态"},
          {prop: "currentIncome", title: "现有收益额", valueType: 'n'},
          {prop: "freezeEarnings", title: "冻结收益", valueType: 'n'},
          {prop: "withdrawableIncome", title: "可提现收益", valueType: 'n'},
          {prop: "accountStatusContent", title: "账户状态"},
        ],
        dataSource: tB_data,
        fileName: '用户礼物收益账户列表'
      }
      this.setState({exportLoading: false});
      Json2Excel(option)
    } else {
      React.$message({
        type: "warning",
        content: "导出操作失败,请重试",
      });
      this.setState({exportLoading: false});
    }
  }
  render() {
    const {
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total,
      searchOption,
      form_show,
      exportLoading,
      isvideoModalVisible, videoAddress
    } = this.state;
    return (
      <div className={"p-layout-box commodity-content"}>
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
          <TheButton
              haspermi={['myPocket:userBalance:export']}
              size="middle"
              onClick={() => this.toExport()}
              type="default"
              loading={exportLoading}
          >
            导出
          </TheButton>
        </TheQueryForm>
        用户礼物收益账户列表
        <TheTable
          columns={columns}
          dataSource={dataSource}
        />
        <ThePagination
          pageNo={pageNo}
          pageSize={pageSize}
          total={total}
          pageChange={this.pageChange}
        />
        {isvideoModalVisible ?
          <Modal visible={isvideoModalVisible} onOk={this.videoOk} onCancel={this.videoOk}>
            <VideoPlayer src={videoAddress} />
          </Modal> : null}
      </div>
    );
  }
}

export default screenAD;
